<?php
/*
 * @Description: 统一返回格式
 * @ComposerRequire: 
 * @ComposerRemove: 
 * @Author: 阿海 <764882431@qq.com>
 * @Date: 2020-10-29 09:29:25
 * @LastEditTime: 2021-07-13 15:45:49
 * @LastEditors: 阿海
 */
namespace builder;

class ApiResult {

   //消息提示的语言设置
   private $lang = '';//en|zh-ch

   //消息提示
   private $codeMsg = [];

   //HTTP状态码
   private $httpCode = [];

   public function __construct(){
       //如果基于tp框架可以使用引入配置的方式 -- $code = config('code.');
       $code = $this->apiResultCode();
       $this->lang = $code['lang'];
       $this->codeMsg = $code[$code['lang']];
       $this->httpCode = $this->httpStatueCode();
   }

   /**
    * @param string $msg  返回的提示内容
    * @param string|array $data 返回的数据 如果设置了msg,将代替原来的提示信息,如果想要设置其他的数据与返回值data同级，只需要$data=['data'=>'','其他的键名'=>'']
    * @param int $httpCode 状态码
    */
   public function echoJson($code=null,  $data = [],$httpCode=200)
   {
       $this->header();
       if(isset($this->httpCode[$httpCode])){
           header($this->httpCode[$httpCode]);
       }
       
        //替换原来的提示信息
        if(!(isset($data['msg']) && !empty($data['msg']))){
            $data['msg'] = $this->codeMsg[$code];
       }
     
       $results = ['code' => $code !== null?$code:'','msg' => isset($data['msg'])?$data['msg']:'丢失code码.'];
       
       $results = isset($data['data'])?array_merge($results,$data):array_merge($results,['data'=>$data]);

       if(isset($results['data']['msg'])){
            unset($results['data']['msg']);
        }
        
    //    $this->writeRequest($results['code'],$results['msg']); 
       echo json_encode($results, JSON_UNESCAPED_UNICODE);
       exit;
   }

   /**
    * @param  string  $msg 返回的提示内容
    * @param string|array  $data 返回的数据 如果设置了msg,将代替原来的提示信息
    */
   public function returnArray($code=null,  $data = []){

       //替换原来的提示信息
       if(!(isset($data['msg']) && !empty($data['msg']))){
            $data['msg'] = $this->codeMsg[$code];
       }
       
       $results = ['code' => $code !== null?$code:'','msg' => isset($data['msg'])?$data['msg']:'丢失code码'];
       
       $results = isset($data['data'])?array_merge($results,$data):array_merge($results,['data'=>$data]);

       if(isset($results['data']['msg'])){
            unset($results['data']['msg']);
       }
    
       return $results;
   }

   /**
    * 将数组转json输出 
    */
    public function toJson($array=[], $httpCode = 200){
        $this->header();
        if(isset($this->httpCode[$httpCode])){
            header($this->httpCode[$httpCode]);
        }
        echo json_encode($array, JSON_UNESCAPED_UNICODE);
        // if(isset($array['code']) && isset($array['msg'])){
        //     $this->writeRequest($array['code'],$array['msg']);
        // }
        exit;
    }

    /**
    * 将json字符串转数组
    */
    public function toArray($jsonString=''){
        return json_decode($jsonString,true);
    }

   /**
    * 记录请求日志--
    */
    // private function writeRequest( $code = 0, $msg = '请求成功')
    // {
    //     try{
                    
    //     }catch(\Exception $e){
           
    //     }   
    // }

    /**
    * 接口请求-- header 头
    */
   private function header()
   {
       header('content-type:application/json;charset=utf-8');
       // 指定允许其他域名访问  *:表示任意域名，可以直接指定域名。
       header('Access-Control-Allow-Origin:'.request()->domain());
       // 响应类型
       header('Access-Control-Allow-Methods:POST,GET');

       header('X-Powered-By:builder');
       // 响应头设置
       header('Access-Control-Allow-Headers:x-requested-with,content-type');
       //过滤options请求
       if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
           exit;
       }
   }

   /**
    * 返回码设置
    */
    public function apiResultCode()
    {
        return [
            //选择语言提示
            'lang'=>'zh-cn',
            //中文提示
            'zh-cn'=>[
                //常规提示
                0=>'请求成功。',
                1=>'系统错误！',//代码出错500
                2=>'系统繁忙！',//请求过于频繁
                3=>'ERROR',//自定义错误提示信息
                4=>'必须使用POST请求！',
                5=>'必须使用GET请求！',
                //构建器错误码
                70001=>'未指定构建器名称',
                70002=>'构建器不存在',
                70003=>'缺少hash参数',
        
            ],
            //English Tips
            'en'=>[
                0=>'OK.',
                1=>'System Error!',
                2=>'System Busy!',
                3=>'Requires Use Of HTTPS!',
                4=>'POST Request Must Be Used!',
                5=>'GET Request Must Be Used!',
            ]
       ];
    }

   /**
    * http状态码设置
    */
   private function httpStatueCode()
   {
        return [
            100 => "HTTP/1.1 100 Continue",
            101 => "HTTP/1.1 101 Switching Protocols",
            200 => "HTTP/1.1 200 OK",
            201 => "HTTP/1.1 201 Created",
            202 => "HTTP/1.1 202 Accepted",
            203 => "HTTP/1.1 203 Non-Authoritative Information",
            204 => "HTTP/1.1 204 No Content",
            205 => "HTTP/1.1 205 Reset Content",
            206 => "HTTP/1.1 206 Partial Content",
            300 => "HTTP/1.1 300 Multiple Choices",
            301 => "HTTP/1.1 301 Moved Permanently",
            302 => "HTTP/1.1 302 Found",
            303 => "HTTP/1.1 303 See Other",
            304 => "HTTP/1.1 304 Not Modified",
            305 => "HTTP/1.1 305 Use Proxy",
            307 => "HTTP/1.1 307 Temporary Redirect",
            400 => "HTTP/1.1 400 Bad Request",
            401 => "HTTP/1.1 401 Unauthorized",
            402 => "HTTP/1.1 402 Payment Required",
            403 => "HTTP/1.1 403 Forbidden",
            404 => "HTTP/1.1 404 Not Found",
            405 => "HTTP/1.1 405 Method Not Allowed",
            406 => "HTTP/1.1 406 Not Acceptable",
            407 => "HTTP/1.1 407 Proxy Authentication Required",
            408 => "HTTP/1.1 408 Request Time-out",
            409 => "HTTP/1.1 409 Conflict",
            410 => "HTTP/1.1 410 Gone",
            411 => "HTTP/1.1 411 Length Required",
            412 => "HTTP/1.1 412 Precondition Failed",
            413 => "HTTP/1.1 413 Request Entity Too Large",
            414 => "HTTP/1.1 414 Request-URI Too Large",
            415 => "HTTP/1.1 415 Unsupported Media Type",
            416 => "HTTP/1.1 416 Requested range not satisfiable",
            417 => "HTTP/1.1 417 Expectation Failed",
            500 => "HTTP/1.1 500 Internal Server Error",
            501 => "HTTP/1.1 501 Not Implemented",
            502 => "HTTP/1.1 502 Bad Gateway",
            503 => "HTTP/1.1 503 Service Unavailable",
            504 => "HTTP/1.1 504 Gateway Time-out"
        ];
   }
 
  
}